package routes

import (
	"github.com/gin-gonic/gin"
	"tieup/internal/api/handler"
	"tieup/internal/config"
	"tieup/internal/middleware"
	"tieup/internal/repository"
	"tieup/internal/service"

	"gorm.io/gorm"
)

func SetupRouter(db *gorm.DB, cfg config.Config) *gin.Engine {
	r := gin.New()

	// 设置中间件
	r.Use(gin.Recovery())      // 崩溃恢复
	r.Use(middleware.Logger()) // 自定义日志
	// r.Use(middleware.RateLimitMiddleware(cfg.RateLimit)) // 限流

	// 初始化依赖
	userRepo := repository.NewUserRepository(db)
	userService := service.NewUserService(userRepo)
	userHandler := handler.NewUserHandler(userService, cfg)

	// 公共路由
	public := r.Group("/api")
	{
		public.POST("/register", userHandler.RegisterUser)
		public.POST("/login", userHandler.Login)
		public.POST("/refresh", userHandler.RefreshToken) // 新增刷新令牌端点
	}

	// 需要认证的路由
	authGroup := r.Group("/api")
	authGroup.Use(middleware.AuthMiddleware(cfg.Auth))
	{
		authGroup.GET("/profile", userHandler.GetProfile)
		authGroup.POST("/logout", userHandler.Logout) // 新增登出端点
	}

	return r
}
